package com.youfang.sixthmedia.ui.weibo;

import java.net.URI;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import org.json.JSONObject;

import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;

import com.gzit.utils.AndroidUtils;
import com.gzit.utils.StringUtils;
import com.youfang.sixthmedia.common.YoufangContext;
import com.youfang.sixthmedia.ui.weibo.sina.SinaWeiboOAuth2Activity;
import com.youfang.sixthmedia.ui.weibo.sina.Utility;

public class SinaWeiboActivity extends WeiboActivity {

	private String accessToken = "";

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		this.init();
	}

	protected void init() {

	}
	



	protected void gotoOAuthActivity() {
		// weibo.authorize(this, new AuthDialogListener());
		Intent intent = new Intent();
		intent.setClass(this, SinaWeiboOAuth2Activity.class);
		this.startActivityForResult(intent, CODE_OAUTH_ACTIVITY);
	}

	// ///////////////////////
	// after oauth
	protected void onOAuthCallback(boolean ok) {

		if (ok) {

			// Bundle[{uid=1753131565, expires_in=86399, remind_in=86399,
			// access_token=2.00ZbxduB01hhLkc50912c82cfGXWAC}]
			accessToken = oAuthResult.getString("access_token");
			String expires_in = oAuthResult.getString("expires_in");

			Editor editor = YoufangContext.prepare();
			editor.putString("sina_token", accessToken);

			// oauth expired in XX second,we use this infomation to
			// calculate the expired date
			editor.putLong("sina_expired", Long.parseLong(expires_in) * 1000
					+ System.currentTimeMillis() - 60 * 60 * 1000);

			editor.commit();

		}
	}
	
	protected void clearStoreSP() {
		
		Editor editor = YoufangContext.prepare();
		editor.remove("sina_token");
		editor.remove("sina_expired");
		editor.remove("sina_nick");
		editor.clear();

	}

	protected boolean isAlreadyAuthed() {

		SharedPreferences sp = YoufangContext.getSharedPreferences();
		accessToken = sp.getString("sina_token", "");
		long expired = sp.getLong("sina_expired", -1);

		if (StringUtils.isBlank(accessToken)) {
			return false;
		}

		// expired?
		if (System.currentTimeMillis() > expired) {
			return false;
		}

		return true;
	}

	protected String getNickName() {
		return YoufangContext.getSharedPreferences().getString("sina_nick", "");
	}

	protected boolean sendWeibo(final String content, final String picPath) {

		new WeiboTask(this) {

			@Override
			boolean doTask(String... params) {
				return _syncSendWeibo(content, picPath);
			}

			@Override
			void callback(boolean result) {
				AndroidUtils.toastShort(result ? "微博发送成功" : "微博发送失败");
			}
		}.execute("");

		return true;

	}

	private boolean _syncSendWeibo(String content, String picPath) {
		// String url = Weibo.SERVER + "statuses/upload.json";
		String url = Utility.SERVER + "statuses/update.json";
		HttpClient httpclient = Utility.getNewHttpClient(this);
		try {

			HttpPost httpPost = new HttpPost(new URI(url));

			List<BasicNameValuePair> pairs = new ArrayList<BasicNameValuePair>();
			pairs.add(new BasicNameValuePair("source", Utility.CONSUMER_KEY));
			pairs.add(new BasicNameValuePair("access_token", this.accessToken));
			pairs.add(new BasicNameValuePair("status", content));
			httpPost.setEntity(new UrlEncodedFormEntity(pairs, HTTP.UTF_8));
			HttpResponse resp = httpclient.execute(httpPost);
			byte[] resultBytes = EntityUtils.toByteArray(resp.getEntity());
			String message = new String(resultBytes, HTTP.UTF_8);
			JSONObject json = new JSONObject(message);
			if (json.has("error_code")) {
				int retCode = json.getInt("error_code");
				if (retCode != 0) {
					return false;
				}
			}

			// post successfully,now get the user info
			JSONObject userJSON = json.getJSONObject("user");
			String nickName = userJSON.getString("screen_name");
			if (StringUtils.isBlank(nickName)) {
				nickName = userJSON.getString("name");
			}

			// save nick_name
			Editor editor = YoufangContext.prepare();
			editor.putString("sina_nick", nickName);
			editor.commit();

		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}

		return true;

	}

	// ///////////////////////
	private Bundle oAuthResult;
	private static final int CODE_OAUTH_ACTIVITY = 1;

	protected void onActivityResult(int requestCode, int resultCode, Intent data) {

		switch (requestCode) {
		case CODE_OAUTH_ACTIVITY:

			if (resultCode == Activity.RESULT_OK) {
				oAuthResult = data.getExtras();
				onOAuthCallback(true);
				return;
			}

			onOAuthCallback(false);

			break;

		}

	};

}
